<template>
  <div style="background-color: #fff; padding: 20px">
    <div>
      <ElButton type="primary" @click="onSaveClicked">确定</ElButton>
    </div>
    <div style="margin-top: 20px">
      <ElForm :model="form" ref="formRef" status-icon>
        <ElFormItem label="起始时间" :label-width="labelWidth" prop="occurrenceTime">
          <el-date-picker v-model="form.occurrenceTime" value-format="YYYY-MM-DD" :disabled-date="occurrenceTimeDisabledDate" />
        </ElFormItem>
      </ElForm>
    </div>
  </div>
</template>

<script setup lang="ts" name="ZLFireTime">
import { onMounted, ref, unref } from 'vue'
import { ElForm, ElFormItem } from 'element-plus'
import { FireTime, getFireTimeDetail, saveOrUpdateFireTime } from '@api/tby/fire/fireTime'
import { ElMessage } from 'element-plus'
import { dateFormat } from '@api/tby/common/common'

const labelWidth = 120
const form = ref<Partial<FireTime.Form>>({})

const onSaveClicked = () => {
  if (!form.value.occurrenceTime) {
    ElMessage({
      type: 'error',
      message: '请选择起始时间'
    })
    return
  }
  const formData = { ...unref(form) }
  saveOrUpdateFireTime(formData).then(() => {
    ElMessage({
      type: 'success',
      message: '保存成功'
    })
    loadDetail()
  })
}

/**限制使用时间不能晚于当前时间 */
const occurrenceTimeDisabledDate = (time: any) => {
  let start = new Date(dateFormat(time.getTime(), 'yyyy-MM-dd')).getTime()
  let end = new Date(dateFormat(new Date().getTime(), 'yyyy-MM-dd')).getTime()
  return start > end
}

const loadDetail = () => {
  getFireTimeDetail().then(({ data }) => {
    form.value = data
    form.value.occurrenceTime = form.value.occurrenceTimeFormat
  })
}

onMounted(() => {
  loadDetail()
})
</script>
